<template>
  <div class="paging-container">
    <app-select
      :value="size"
      position="top"
      @change="pageSizeChange"
      style="min-width:20px;width:25px;"
    >
      <app-option :value="5" label="5"></app-option>
      <app-option :value="10" label="10"></app-option>
      <app-option :value="20" label="20"></app-option>
    </app-select>
    <div @click="pageChange(current - 1)" class="paging-btn">
      {{ $t('paging.pre') }}
    </div>
    <ul class="page-num-container">
      <li
        class="page-num"
        :active="current === item"
        v-for="(item, index) in pageList"
        :key="index"
        @change="pageChange(item)"
      >
        {{ item }}
      </li>
    </ul>
    <div @click="pageChange(current + 1)" class="paging-btn">
      {{ $t('paging.next') }}
    </div>
    <div class="paging-total">{{$t('paging.total',{total:total})}}</div>
  </div>
</template>
<script>
import AppSelect from '@/components/common/select/AppSelect'
import AppOption from '@/components/common/select/AppOption'
export default {
  data () {
    return { size: this.defaultSize || 10, current: 1 }
  },
  components: { AppSelect, AppOption },
  props: {
    total: { type: Number },
    defaultSize: { type: Number }
  },
  computed: {
    pageList: function () {
      const result = []
      const allPage = Math.ceil(this.total / this.size)
      if (allPage > 9) {
        const half = allPage / 2
        for (let i = 1; i <= allPage; i++) {
          if (
            (i > 0 && i < 3) ||
            (this.current - 1 <= i && i <= this.current + 1) ||
            (half - 1 <= i && i <= half + 1) ||
            i >= allPage - 1
          ) {
            result.push(i)
          } else if (result[result.length - 1] !== '...') {
            result.push('...')
          }
        }
      } else {
        for (let i = 1; i <= allPage; i++) {
          result.push(i)
        }
      }
      return result
    }
  },
  methods: {
    pageSizeChange (value) {
      this.size = value
      this.pageChange(1)
    },
    pageChange (pageNum) {
      if (pageNum > 0 && pageNum <= this.pageList.length) {
        this.current = pageNum
        this.$emit('page-handler', this.size, (pageNum - 1) * this.size)
      }
    }
  }
}
</script>
